"""
Copyright 2009 Texas A&M University
 
Licensed under the Apache License, Version 2.0 (the "License"); you may not use 
this file except in compliance with the License. You may obtain a copy of the 
License at

http://www.apache.org/licenses/LICENSE-2.0
  
Unless required by applicable law or agreed to in writing, software distributed 
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR 
CONDITIONS OF ANY KIND, either express or implied. See the License for the 
specific language governing permissions and limitations under the License. 
"""

from zope.interface import implements

from meercat.interfaces import IResource, IInstance, IPickleable



class Resource(object):
    """ A basic implementation of the IResource interface. All data is stored
    as attributes of the object """
    implements(IResource, IPickleable)
    
    def __init__(self,
                 identifier=None,
                 instances=[]):
        self._identifier = identifier
        self._instances  = frozenset(map(lambda i: IPickleable(IInstance(i)),
                                         instances))
        for i in self._instances:
            if i.getResource() != self:
                i._resource = self
    
    def __len__(self):
        return len(self._instances)
    
    def __iter__(self):
        return self._instances.__iter__()
    
    def getIdentifier(self):
        return self._identifier
    
    def getMetadata(self):
        metadata = []
        
        for instance in self._instances:
            metadata.extend(instance.getMetadata())
        
        return frozenset(metadata)
    
    def getLastModified(self):
        return max(map(lambda i: i.getLastModified(), self))
    
    def isActive(self):
        for instance in self._instances:
            if instance.isActive():
                return True
        
        return False
